<template>
  <view class="calendar-card">
    <view class="card-header">
      <view class="greeting-info">
        <view class="greeting-text">{{ greeting }}</view>
        <view class="today-info"
          >今天是{{ currentDate }} {{ currentWeekday }}</view
        >
      </view>
      <view class="settings-icon" @click="openWorkTimeSettings">
        <FeatherIcon name="settings" size="20" color="#fff" />
      </view>
    </view>

    <!-- 工作日显示下班倒计时，休息日只显示一条休息日信息 -->
    <block v-if="isWorkday">
      <view class="time-countdown">
        <view class="countdown-text">
          <block
            v-if="
              holidayInfo && holidayInfo.type && holidayInfo.type.type === 2
            "
          >
            {{ "今天是" + holidayInfo.type.name + "，" }}
          </block>
          <block v-if="hoursUntilOffWork < 0">
            距离您上班还有
            <text class="time-count">{{ Math.abs(hoursUntilOffWork) }}</text>
            小时
          </block>
          <block v-else-if="hoursUntilOffWork > 0">
            距离您下班还有
            <text class="time-count">{{ hoursUntilOffWork }}</text> 小时
          </block>
          <block v-else> 下班啦！今天辛苦了，好好享受休息时光吧~ </block>
        </view>
      </view>

      <!-- 优先显示下一个节假日信息，没有节假日时显示距离周末信息 -->
      <view class="next-holiday" v-if="getNextHolidayText">
        <view class="next-holiday-text">
          <FeatherIcon
            name="calendar"
            size="16"
            color="#fff"
            class="holiday-icon"
          />
          <text>{{ getNextHolidayText }}</text>
        </view>
      </view>
      <view class="weekend-countdown" v-else-if="daysUntilWeekend > 0">
        <view class="countdown-text">
          再坚持
          <text class="day-count">{{ daysUntilWeekend }}</text> 天就到{{
            weekendText
          }}啦！
        </view>
      </view>
    </block>

    <!-- 休息日信息 -->
    <block v-else>
      <view class="time-countdown">
        <view class="countdown-text">
          {{ getHolidayText || "今天是休息日，好好放松吧！" }}
        </view>
      </view>
    </block>

    <!-- 下一个节假日信息 - 在休息日也显示，但不要重复显示 -->
    <view class="next-holiday" v-if="!isWorkday && getNextHolidayText">
      <view class="next-holiday-text">
        <FeatherIcon
          name="calendar"
          size="16"
          color="#fff"
          class="holiday-icon"
        />
        <text>{{ getNextHolidayText }}</text>
      </view>
    </view>

    <view class="daily-quote">
      <text class="quote-text">{{ dailyQuote }}</text>
      <text class="quote-author">—— {{ quoteAuthor }}</text>
    </view>

    <!-- 工作时间设置弹窗 -->
    <view class="work-settings-modal" v-if="showWorkSettings">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">工作时间设置</text>
          <view class="close-icon" @click="closeWorkTimeSettings">
            <FeatherIcon name="x" size="24" color="#333" />
          </view>
        </view>

        <view class="settings-form">
          <view class="form-row">
            <view class="form-item">
              <text class="form-label">上班时间</text>
              <picker
                mode="time"
                :value="workStartTime"
                @change="onWorkStartTimeChange"
              >
                <view class="time-picker">{{ workStartTime }}</view>
              </picker>
            </view>

            <view class="form-item">
              <text class="form-label">下班时间</text>
              <picker
                mode="time"
                :value="workEndTime"
                @change="onWorkEndTimeChange"
              >
                <view class="time-picker">{{ workEndTime }}</view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="form-label">周末设置</text>
            <picker
              :range="weekendOptions"
              :value="weekendTypeIndex"
              @change="onWeekendTypeChange"
            >
              <view class="weekend-picker">{{
                weekendOptions[weekendTypeIndex]
              }}</view>
            </picker>
          </view>
        </view>

        <view class="save-button" @click="saveWorkSettings">保存设置</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from "vue";
import FeatherIcon from "@/components/FeatherIcon.vue";
import { showSuccess } from "@/utils/common.js";

const emit = defineEmits(["update-info"]);

// 当前日期和星期
const currentDate = ref("");
const currentWeekday = ref("");
const daysUntilWeekend = ref(0);
const greeting = ref(""); // 问候语
const weekendText = ref("周末"); // 周末文本
const isWorkday = ref(true); // 是否是工作日
const hoursUntilOffWork = ref(0); // 距离下班的小时数
const holidayInfo = ref(null); // 节假日信息
const nextHoliday = ref(null); // 下一个节假日信息
// 每日一言相关
const dailyQuote = ref("");
const quoteAuthor = ref("");

// 工作时间设置相关
const showWorkSettings = ref(false);
const workStartTime = ref("09:00");
const workEndTime = ref("18:00");
const weekendTypeIndex = ref(0);
const weekendOptions = ["双休(周六周日)", "单休(周日)", "自定义"];

// 定时器ID
let timerID = null;

// 获取每日一言
const fetchDailyQuote = async () => {
  try {
    const response = await uni.request({
      url: "https://international.v1.hitokoto.cn/?c=d&c=i&c=k&min_length=20&max_length=50",
      method: "GET",
    });
    if (response.data) {
      dailyQuote.value = response.data.hitokoto;
      quoteAuthor.value =
        response.data.from_who || response.data.from || "佚名";
    }
  } catch (error) {
    console.error("获取每日一言失败", error);
    // 设置一些默认的名言
    const defaultQuotes = [
      {
        text: "生活就像一盒巧克力，你永远不知道下一颗是什么味道。",
        author: "阿甘正传",
      },
      { text: "种一棵树最好的时间是十年前，其次是现在。", author: "中国谚语" },
      { text: "不要等待机会，而要创造机会。", author: "林肯" },
      {
        text: "与其用华丽的外衣装饰自己，不如用知识武装自己。",
        author: "莎士比亚",
      },
      { text: "把时间用在思考上是最能节省时间的事情。", author: "卡曾斯" },
    ];
    const randomQuote =
      defaultQuotes[Math.floor(Math.random() * defaultQuotes.length)];
    dailyQuote.value = randomQuote.text;
    quoteAuthor.value = randomQuote.author;
  }
};

// 打开工作时间设置
const openWorkTimeSettings = () => {
  showWorkSettings.value = true;
};

// 关闭工作时间设置
const closeWorkTimeSettings = () => {
  showWorkSettings.value = false;
};

// 更新上班时间
const onWorkStartTimeChange = (e) => {
  workStartTime.value = e.detail.value;
};

// 更新下班时间
const onWorkEndTimeChange = (e) => {
  workEndTime.value = e.detail.value;
};

// 更新周末类型
const onWeekendTypeChange = (e) => {
  weekendTypeIndex.value = parseInt(e.detail.value);
};

// 保存工作时间设置
const saveWorkSettings = () => {
  // 保存设置到本地存储
  uni.setStorageSync("workStartTime", workStartTime.value);
  uni.setStorageSync("workEndTime", workEndTime.value);
  uni.setStorageSync("weekendTypeIndex", weekendTypeIndex.value);

  // 更新日期和时间信息
  updateDateInfo();

  // 关闭设置窗口
  closeWorkTimeSettings();

  // 显示保存成功提示
  showSuccess("设置已保存");
};

// 根据当前时间更新问候语
const updateGreeting = () => {
  const now = new Date();
  const hours = now.getHours();
  const nickname = "鱼油"; // 可以从用户信息中获取，这里使用固定值

  if (hours >= 5 && hours < 11) {
    greeting.value = `Hi，${nickname}，早上好！`;
  } else if (hours >= 11 && hours < 14) {
    greeting.value = `Hi，${nickname}，中午好！`;
  } else if (hours >= 14 && hours < 18) {
    greeting.value = `Hi，${nickname}，下午好！`;
  } else if (hours >= 18 && hours < 23) {
    greeting.value = `Hi，${nickname}，晚上好！`;
  } else {
    greeting.value = `Hi，${nickname}，夜深了，注意休息哦！`;
  }
};

// 计算距离下班的时间
const calculateTimeUntilOffWork = () => {
  const now = new Date();
  const startTimeParts = workStartTime.value.split(":");
  const endTimeParts = workEndTime.value.split(":");

  // 验证时间格式
  if (startTimeParts.length !== 2 || endTimeParts.length !== 2) {
    console.error("工作时间格式不正确");
    return;
  }

  const startHour = parseInt(startTimeParts[0]);
  const startMinute = parseInt(startTimeParts[1]);
  const endHour = parseInt(endTimeParts[0]);
  const endMinute = parseInt(endTimeParts[1]);

  // 验证时间值是否有效
  if (
    isNaN(startHour) ||
    isNaN(startMinute) ||
    isNaN(endHour) ||
    isNaN(endMinute) ||
    startHour < 0 ||
    startHour > 23 ||
    startMinute < 0 ||
    startMinute > 59 ||
    endHour < 0 ||
    endHour > 23 ||
    endMinute < 0 ||
    endMinute > 59
  ) {
    console.error("工作时间值无效");
    return;
  }

  const startTime = new Date();
  startTime.setHours(startHour, startMinute, 0);

  const offWorkTime = new Date();
  offWorkTime.setHours(endHour, endMinute, 0);

  // 如果还没到上班时间，显示距离上班时间
  if (now.getTime() < startTime.getTime()) {
    const diffMs = startTime.getTime() - now.getTime();
    const diffHours = diffMs / (1000 * 60 * 60);
    hoursUntilOffWork.value = -Math.round(diffHours * 10) / 10; // 使用负数表示距离上班时间
    return;
  }

  // 如果已经过了下班时间，显示下班后的提示
  if (now.getTime() > offWorkTime.getTime()) {
    hoursUntilOffWork.value = 0;
    return;
  }

  // 计算剩余小时数，保留一位小数
  const diffMs = offWorkTime.getTime() - now.getTime();
  const diffHours = diffMs / (1000 * 60 * 60);
  hoursUntilOffWork.value = Math.max(0, Math.round(diffHours * 10) / 10);
};

// 判断今天是否是工作日
const checkIfWorkday = async () => {
  try {
    // 获取当前日期
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0");
    const day = String(now.getDate()).padStart(2, "0");
    const dateString = `${year}-${month}-${day}`;

    // 调用节假日API
    const response = await uni.request({
      url: `https://timor.tech/api/holiday/info/${dateString}`,
      method: "GET",
    });

    if (response.statusCode === 200 && response.data.code === 0) {
      // 保存节假日信息
      holidayInfo.value = response.data;

      // 根据API返回判断是否为工作日
      // type.type: 0表示工作日，1表示周末，2表示节日，3表示调休
      if (response.data.type && response.data.type.type !== undefined) {
        // 工作日(0)或调休日(3)需要上班，其他情况都是休息
        isWorkday.value =
          response.data.type.type === 0 || response.data.type.type === 3;
      } else {
        // API调用失败时回退到本地判断
        const day = now.getDay(); // 0是周日，6是周六

        // 根据用户设置的周末类型判断
        if (weekendTypeIndex.value === 0) {
          // 双休
          isWorkday.value = day !== 0 && day !== 6;
        } else if (weekendTypeIndex.value === 1) {
          // 单休，只有周日休息
          isWorkday.value = day !== 0;
        } else {
          // 自定义，这里简单处理，可以根据需要扩展
          isWorkday.value = day !== 0 && day !== 6;
        }
      }
    } else {
      // API调用失败时回退到本地判断
      const day = now.getDay(); // 0是周日，6是周六

      // 根据用户设置的周末类型判断
      if (weekendTypeIndex.value === 0) {
        // 双休
        isWorkday.value = day !== 0 && day !== 6;
      } else if (weekendTypeIndex.value === 1) {
        // 单休，只有周日休息
        isWorkday.value = day !== 0;
      } else {
        // 自定义，这里简单处理，可以根据需要扩展
        isWorkday.value = day !== 0 && day !== 6;
      }
    }
  } catch (error) {
    console.error("获取节假日信息失败", error);

    // 发生错误时回退到本地判断
    const now = new Date();
    const day = now.getDay(); // 0是周日，6是周六

    // 根据用户设置的周末类型判断
    if (weekendTypeIndex.value === 0) {
      // 双休
      isWorkday.value = day !== 0 && day !== 6;
    } else if (weekendTypeIndex.value === 1) {
      // 单休，只有周日休息
      isWorkday.value = day !== 0;
    } else {
      // 自定义，这里简单处理，可以根据需要扩展
      isWorkday.value = day !== 0 && day !== 6;
    }
  }
};

// 更新周末信息
const updateWeekendInfo = () => {
  const now = new Date();
  const day = now.getDay(); // 0是周日，6是周六

  // 根据周末设置判断
  if (weekendTypeIndex.value === 0) {
    // 双休
    weekendText.value = "周末";
    // 如果今天是周六或周日，距离周末天数为0
    if (day === 0 || day === 6) {
      daysUntilWeekend.value = 0;
    } else {
      // 否则计算距离周六的天数
      daysUntilWeekend.value = 6 - day;
    }
  } else if (weekendTypeIndex.value === 1) {
    // 单休
    weekendText.value = "休息日";
    // 如果今天是周日，距离休息日天数为0
    if (day === 0) {
      daysUntilWeekend.value = 0;
    } else {
      // 否则计算距离周日的天数
      daysUntilWeekend.value = 7 - day;
    }
  } else {
    // 自定义，这里简单处理为双休
    weekendText.value = "周末";
    if (day === 0 || day === 6) {
      daysUntilWeekend.value = 0;
    } else {
      daysUntilWeekend.value = 6 - day;
    }
  }
};

// 更新日期信息
const updateDateInfo = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const day = now.getDate();

  // 设置当前日期
  currentDate.value = `${month}月${day}日`;

  // 设置星期
  const weekdays = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];
  currentWeekday.value = weekdays[now.getDay()];

  // 更新问候语
  updateGreeting();

  // 检查是否是工作日 - 使用API版本
  checkIfWorkday();

  // 计算距离下班的时间
  calculateTimeUntilOffWork();

  // 计算距离周末的天数和更新周末文本
  updateWeekendInfo();

  // 获取下一个节假日信息
  getNextHoliday();
};

// 获取节假日文本
const getHolidayText = computed(() => {
  if (
    holidayInfo.value &&
    holidayInfo.value.type &&
    holidayInfo.value.type.type === 2
  ) {
    // 如果是节日
    return `今天是${holidayInfo.value.type.name}，祝您节日快乐！`;
  } else if (!isWorkday.value) {
    return "今天是休息日，好好放松吧！";
  }
  return "";
});

// 获取下一个节假日信息
const getNextHoliday = async () => {
  try {
    // 调用节假日API
    const response = await uni.request({
      url: `https://timor.tech/api/holiday/next`,
      method: "GET",
    });

    if (response.statusCode === 200 && response.data.code === 0) {
      // 保存下一个节假日信息
      nextHoliday.value = response.data;
    }
  } catch (error) {
    console.error("获取下一个节假日信息失败", error);
    nextHoliday.value = null;
  }
};

// 下一个节假日文本
const getNextHolidayText = computed(() => {
  // 如果当前是节日，不显示下一个节假日信息
  if (
    holidayInfo.value &&
    holidayInfo.value.type &&
    holidayInfo.value.type.type === 2
  ) {
    return "";
  }

  // 如果获取到了下一个节假日信息
  if (nextHoliday.value && nextHoliday.value.holiday) {
    const holiday = nextHoliday.value.holiday;
    return `距离${holiday.name}还有${holiday.rest}天`;
  }

  // 如果没有下一个节假日信息，且是工作日，显示距离周末的信息
  if (isWorkday.value && daysUntilWeekend.value > 0) {
    return `距离${weekendText.value}还有${daysUntilWeekend.value}天`;
  }

  return "";
});

// 加载工作时间设置
const loadWorkSettings = () => {
  const savedStartTime = uni.getStorageSync("workStartTime");
  const savedEndTime = uni.getStorageSync("workEndTime");
  const savedWeekendType = uni.getStorageSync("weekendTypeIndex");

  // 设置默认值
  workStartTime.value = savedStartTime || "09:00";
  workEndTime.value = savedEndTime || "18:00";

  if (savedWeekendType !== "" && savedWeekendType !== null) {
    weekendTypeIndex.value = parseInt(savedWeekendType);
  }
};

// 初始化加载设置
onMounted(async () => {
  // 加载工作时间设置
  loadWorkSettings();

  // 获取每日一言
  fetchDailyQuote();

  // 更新日期和时间信息
  updateDateInfo();

  // 设置定时器，每分钟更新一次时间信息
  timerID = setInterval(() => {
    updateDateInfo();
  }, 60000);
});

onUnmounted(() => {
  // 清除定时器
  if (timerID) {
    clearInterval(timerID);
  }
});
</script>

<style lang="scss">
.calendar-card {
  margin: 24rpx;
  padding: 30rpx;
  background: linear-gradient(to right, #ffb74d, #ff9800);
  border-radius: 20rpx;
  color: #fff;
  box-shadow: 0 10rpx 20rpx rgba(255, 152, 0, 0.2);
  position: relative;
  overflow: hidden;

  &::after {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    width: 200rpx;
    height: 200rpx;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    transform: translate(30%, -30%);
  }

  &::before {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    width: 240rpx;
    height: 240rpx;
    background: rgba(255, 255, 255, 0.08);
    border-radius: 50%;
    transform: translate(-30%, 30%);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
    position: relative;
    z-index: 1;

    .greeting-info {
      display: flex;
      flex-direction: column;
    }

    .greeting-text {
      font-size: 38rpx;
      font-weight: bold;
      margin-bottom: 12rpx;
      text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
    }

    .today-info {
      font-size: 30rpx;
      padding: 8rpx 20rpx;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 30rpx;
      display: inline-block;
    }

    .settings-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.2);
      transition: all 0.3s;
      align-self: flex-start;
      margin-top: 8rpx;

      &:active {
        transform: scale(0.92);
        background-color: rgba(255, 255, 255, 0.3);
      }
    }
  }

  .time-countdown {
    margin-top: 24rpx;
    font-size: 30rpx;
    position: relative;
    z-index: 1;

    .countdown-text {
      animation: fadeIn 0.5s ease-out;

      .time-count {
        font-size: 44rpx;
        font-weight: bold;
        margin: 0 8rpx;
        background: rgba(255, 255, 255, 0.2);
        padding: 0 12rpx;
        border-radius: 8rpx;
        display: inline-block;
        min-width: 60rpx;
        text-align: center;
      }
    }
  }

  .weekend-countdown {
    margin-top: 24rpx;
    font-size: 30rpx;
    position: relative;
    z-index: 1;

    .countdown-text {
      animation: fadeIn 0.7s ease-out;

      .day-count {
        font-size: 44rpx;
        font-weight: bold;
        margin: 0 8rpx;
        background: rgba(255, 255, 255, 0.2);
        padding: 0 12rpx;
        border-radius: 8rpx;
        display: inline-block;
        min-width: 60rpx;
        text-align: center;
      }
    }
  }

  /* 下一个节假日信息样式 */
  .next-holiday {
    margin-top: 24rpx;
    font-size: 28rpx;
    position: relative;
    z-index: 1;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 12rpx;
    padding: 16rpx 20rpx;
    animation: fadeIn 0.8s ease-out;

    .next-holiday-text {
      display: flex;
      align-items: center;

      .holiday-icon {
        margin-right: 10rpx;
      }

      text {
        flex: 1;
      }
    }
  }

  .daily-quote {
    margin-top: 28rpx;
    padding: 20rpx;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 12rpx;
    position: relative;
    z-index: 1;
    border-left: 6rpx solid rgba(255, 255, 255, 0.4);
    animation: fadeIn 0.9s ease-out;

    .quote-text {
      font-size: 28rpx;
      line-height: 1.6;
      display: block;
      margin-bottom: 10rpx;
      text-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.1);
    }

    .quote-author {
      font-size: 24rpx;
      opacity: 0.8;
      display: block;
      text-align: right;
      padding-right: 10rpx;
    }
  }

  /* 工作时间设置弹窗样式 */
  .work-settings-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;

    .modal-content {
      background: #fff;
      border-radius: 20rpx;
      padding: 40rpx;
      width: 80%;
      max-width: 600rpx;
      text-align: center;
      animation: modalPop 0.3s ease-out;
      box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.15);

      .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30rpx;

        .modal-title {
          font-size: 36rpx;
          font-weight: bold;
          color: #333;
        }

        .close-icon {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          background-color: rgba(255, 255, 255, 0.2);
          transition: all 0.3s;
          align-self: flex-start;
          margin-top: 8rpx;

          &:active {
            transform: scale(0.92);
            background-color: rgba(255, 255, 255, 0.3);
          }
        }
      }

      .settings-form {
        margin-bottom: 40rpx;

        .form-row {
          display: flex;
          justify-content: space-between;
          margin-bottom: 24rpx;

          .form-item {
            width: 48%;
          }
        }

        .form-item {
          margin-bottom: 24rpx;
          text-align: left;

          .form-label {
            display: block;
            font-size: 28rpx;
            color: #333;
            margin-bottom: 12rpx;
            font-weight: 500;
          }

          .time-picker,
          .weekend-picker {
            padding: 20rpx;
            border: 1rpx solid #eee;
            border-radius: 10rpx;
            background-color: #f9f9f9;
            width: 100%;
            text-align: center;
            color: #333;
            box-sizing: border-box;
          }
        }
      }

      .save-button {
        background: linear-gradient(135deg, #ff7f50, #ff9800);
        color: #fff;
        padding: 20rpx 60rpx;
        border-radius: 40rpx;
        font-size: 32rpx;
        font-weight: bold;
        display: inline-block;
        box-shadow: 0 4rpx 12rpx rgba(58, 142, 255, 0.3);
        transition: all 0.3s;

        &:active {
          transform: scale(0.96);
          box-shadow: 0 2rpx 6rpx rgba(58, 142, 255, 0.3);
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes modalPop {
  from {
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
